﻿using System;
using System.Collections.Generic;
using LoungeRepo.Contracts.Normalizer;

namespace LoungeRepo.Normalizer
{
    internal partial class ObjectGraphDenormalizer
    {
        private readonly EntityResolutionRequestDelegate resolveEntityReference;
        private readonly Dictionary<string, object> denormalizedObjectCache = new Dictionary<string, object>();


        public ObjectGraphDenormalizer(EntityResolutionRequestDelegate resolveEntityReference)
        {
            this.resolveEntityReference = resolveEntityReference;
        }


        public object Denormalize(INormalizedObject normalizedObject)
        {
            if (normalizedObject.ObjectType.IsArray)
                return DenormalizeArray(normalizedObject);

            return DenormalizeSingleObject(normalizedObject);
        }


        public object DenormalizeArray(INormalizedObject normalizedObject)
        {
            List<INormalizedField> normalizedFields = new List<INormalizedField>(normalizedObject.Fields);

            Array denormalizedArray = CreateDenormalizedArray(normalizedObject, normalizedFields);

            TransferElementsIntoArray(normalizedFields, denormalizedArray);

            return denormalizedArray;
        }

        
        private object DenormalizeSingleObject(INormalizedObject normalizedObject)
        {
            object denormalizedObject = CreateDenormalizedObject(normalizedObject);

            DenormalizeNonTransientFields(normalizedObject, denormalizedObject);

            return denormalizedObject;
        }
    }
}
